-- Lua Battle System - AI决策质量评估器
-- 提供智能的AI决策质量评估和改进建议系统

local Logger = require("utils.logger")
local TableUtils = require("utils.table_utils")

local AIQualityAssessor = {
    -- 评估配置
    config = {
        -- 决策质量权重
        quality_weights = {
            strategic_correctness = 0.35,  -- 战略正确性
            efficiency = 0.25,              -- 效率性
            adaptability = 0.20,            -- 适应性
            resource_management = 0.15,     -- 资源管理
            risk_assessment = 0.05          -- 风险评估
        },

        -- 评分等级
        score_levels = {
            excellent = {min = 90, grade = "A+", description = "卓越决策"},
            good = {min = 80, grade = "A", description = "优秀决策"},
            satisfactory = {min = 70, grade = "B", description = "良好决策"},
            acceptable = {min = 60, grade = "C", description = "可接受决策"},
            poor = {min = 0, grade = "D", description = "需改进决策"}
        },

        -- 评估指标阈值
        thresholds = {
            min_decision_score = 40,
            target_efficiency_ratio = 0.7,
            acceptable_risk_level = 0.3,
            resource_waste_threshold = 0.4
        }
    },

    -- 决策历史记录
    decision_history = {},

    -- 性能指标
    performance_metrics = {
        total_decisions = 0,
        excellent_decisions = 0,
        poor_decisions = 0,
        average_score = 0,
        improvement_trend = {}
    }
}

-- AI质量评估器构造函数
function AIQualityAssessor:new(o)
    local o = o or {}
    setmetatable(o, self)
    self.__index = self
    o:init()
    return o
end

-- 初始化评估器
function AIQualityAssessor:init()
    self.decision_history = {}
    self.performance_metrics = {
        total_decisions = 0,
        excellent_decisions = 0,
        poor_decisions = 0,
        average_score = 0,
        improvement_trend = {}
    }
    Logger.debug("AI质量评估器初始化完成")
end

-- 核心评估函数：全面评估AI决策质量
function AIQualityAssessor:assess_decision_quality(character, battle_state, decision, context)
    if not decision then
        return {
            overall_score = 0,
            grade = "F",
            assessment = "决策为空",
            details = {},
            recommendations = {}
        }
    end

    -- 创建评估上下文
    local assessment_context = self:create_assessment_context(character, battle_state, decision, context)

    -- 执行多维度评估
    local assessment_results = {
        strategic_correctness = self:assess_strategic_correctness(assessment_context),
        efficiency = self:assess_efficiency(assessment_context),
        adaptability = self:assess_adaptability(assessment_context),
        resource_management = self:assess_resource_management(assessment_context),
        risk_assessment = self:assess_risk_assessment(assessment_context)
    }

    -- 计算综合评分
    local overall_score = self:calculate_overall_score(assessment_results)
    local grade_info = self:get_grade_info(overall_score)

    -- 生成改进建议
    local recommendations = self:generate_recommendations(assessment_context, assessment_results)

    -- 构建最终评估结果
    local final_assessment = {
        overall_score = overall_score,
        grade = grade_info.grade,
        grade_description = grade_info.description,
        assessment = self:generate_assessment_summary(assessment_results, overall_score),
        details = assessment_results,
        recommendations = recommendations,
        context = assessment_context,
        timestamp = os.time()
    }

    -- 记录决策历史
    self:record_decision(character, decision, final_assessment)

    return final_assessment
end

-- 创建评估上下文
function AIQualityAssessor:create_assessment_context(character, battle_state, decision, context)
    return {
        character = character,
        battle_state = battle_state,
        decision = decision,
        additional_context = context or {},

        -- 计算关键状态指标
        character_status = {
            health_percentage = character.hp / character.max_hp,
            mp_percentage = character.mp / character.max_mp,
            is_critical_health = character.hp / character.max_hp < 0.3,
            is_low_mp = character.mp / character.max_mp < 0.2
        },

        -- 战斗环境分析
        battle_analysis = self:analyze_battle_environment(battle_state, character),

        -- 决策类型分析
        decision_type = self:analyze_decision_type(decision),

        -- 目标分析
        target_analysis = decision.target and self:analyze_target(character, decision.target, battle_state) or nil
    }
end

-- 分析战斗环境
function AIQualityAssessor:analyze_battle_environment(battle_state, character)
    local analysis = {
        total_allies = 0,
        alive_allies = 0,
        low_health_allies = 0,
        total_enemies = 0,
        alive_enemies = 0,
        low_health_enemies = 0,
        team_advantage = 0,
        urgency_level = "normal"
    }

    -- 统计队友状态
    for _, char in ipairs(battle_state.characters) do
        if char.team_id == character.team_id then
            analysis.total_allies = analysis.total_allies + 1
            if char.is_alive then
                analysis.alive_allies = analysis.alive_allies + 1
                if char.hp / char.max_hp < 0.3 then
                    analysis.low_health_allies = analysis.low_health_allies + 1
                end
            end
        else
            analysis.total_enemies = analysis.total_enemies + 1
            if char.is_alive then
                analysis.alive_enemies = analysis.alive_enemies + 1
                if char.hp / char.max_hp < 0.3 then
                    analysis.low_health_enemies = analysis.low_health_enemies + 1
                end
            end
        end
    end

    -- 计算队伍优势
    if analysis.alive_allies > 0 and analysis.alive_enemies > 0 then
        analysis.team_advantage = analysis.alive_allies / analysis.alive_enemies
    end

    -- 评估紧急程度
    local character_health_percentage = character.hp / character.max_hp
    if character_health_percentage < 0.2 then
        analysis.urgency_level = "critical"
    elseif analysis.low_health_allies > 0 or character_health_percentage < 0.5 then
        analysis.urgency_level = "high"
    elseif analysis.low_health_enemies > 0 and analysis.team_advantage > 1.5 then
        analysis.urgency_level = "opportunity"
    end

    return analysis
end

-- 分析决策类型
function AIQualityAssessor:analyze_decision_type(decision)
    local type_analysis = {
        category = decision.type or "unknown",
        is_offensive = false,
        is_defensive = false,
        is_supportive = false,
        resource_cost = 0
    }

    if decision.type == "skill" and decision.skill then
        if decision.skill.damage and decision.skill.damage.base > 0 then
            type_analysis.is_offensive = true
        end
        if decision.skill.healing and decision.skill.healing.base > 0 then
            type_analysis.is_defensive = true
            type_analysis.is_supportive = true
        end
        if decision.skill.cost and decision.skill.cost.mp then
            type_analysis.resource_cost = decision.skill.cost.mp
        end
    elseif decision.type == "defend" then
        type_analysis.is_defensive = true
    elseif decision.type == "item" then
        type_analysis.is_supportive = true
    end

    return type_analysis
end

-- 分析目标
function AIQualityAssessor:analyze_target(character, target, battle_state)
    return {
        is_ally = target.team_id == character.team_id,
        is_enemy = target.team_id ~= character.team_id,
        health_percentage = target.hp / target.max_hp,
        is_critical_health = target.hp / target.max_hp < 0.3,
        threat_level = self:calculate_threat_level(character, target)
    }
end

-- 计算威胁等级
function AIQualityAssessor:calculate_threat_level(character, target)
    if target.team_id == character.team_id then
        return 0 -- 队友无威胁
    end

    -- 基于攻击力和生命值计算威胁
    local attack_threat = target.attack / character.defense
    local health_threat = target.hp / target.max_hp
    local skill_threat = 0

    if target.skills then
        for _, skill in ipairs(target.skills) do
            if skill.damage and skill.damage.base > 0 then
                skill_threat = skill_threat + skill.damage.base
            end
        end
        skill_threat = skill_threat / #target.skills / character.defense
    end

    return (attack_threat + health_threat + skill_threat) / 3
end

-- 评估战略正确性
function AIQualityAssessor:assess_strategic_correctness(context)
    local score = 50 -- 基础分数
    local factors = {}

    -- 根据紧急程度评估决策类型选择
    if context.battle_analysis.urgency_level == "critical" then
        if context.decision_type.is_defensive then
            score = score + 30
            table.insert(factors, "危机时刻选择防御性决策")
        else
            score = score - 20
            table.insert(factors, "危机时刻未选择防御性决策")
        end
    elseif context.battle_analysis.urgency_level == "opportunity" then
        if context.decision_type.is_offensive then
            score = score + 20
            table.insert(factors, "抓住进攻机会")
        end
    end

    -- 评估目标选择的合理性
    if context.target_analysis then
        if context.decision_type.is_offensive and context.target_analysis.is_enemy then
            if context.target_analysis.is_critical_health then
                score = score + 15
                table.insert(factors, "优先攻击低生命值敌人")
            end
            if context.target_analysis.threat_level > 1.5 then
                score = score + 10
                table.insert(factors, "优先消除高威胁目标")
            end
        elseif context.decision_type.is_supportive and context.target_analysis.is_ally then
            if context.target_analysis.is_critical_health then
                score = score + 20
                table.insert(factors, "优先治疗低生命值队友")
            end
        end
    end

    -- 评估队伍协作
    if context.battle_analysis.low_health_allies > 0 and context.decision_type.is_supportive then
        score = score + 15
        table.insert(factors, "关注队友状态")
    end

    return {
        score = math.max(0, math.min(100, score)),
        factors = factors,
        assessment = self:generate_factor_assessment(score, factors)
    }
end

-- 评估效率性
function AIQualityAssessor:assess_efficiency(context)
    local score = 50
    local factors = {}

    -- 评估资源效率
    if context.decision_type.resource_cost > 0 then
        local efficiency_ratio = 1
        if context.decision_type.is_offensive and context.decision.skill then
            local expected_damage = context.decision.skill.damage.base or 0
            efficiency_ratio = expected_damage / context.decision_type.resource_cost
        elseif context.decision_type.is_defensive and context.decision.skill then
            local expected_healing = context.decision.skill.healing.base or 0
            efficiency_ratio = expected_healing / context.decision_type.resource_cost
        end

        if efficiency_ratio >= self.config.thresholds.target_efficiency_ratio then
            score = score + 25
            table.insert(factors, "高资源效率决策")
        else
            score = score - 15
            table.insert(factors, "资源效率较低")
        end
    else
        score = score + 20
        table.insert(factors, "无消耗决策")
    end

    -- 评估时机选择
    if context.character_status.is_low_mp and context.decision_type.resource_cost > context.character.mp then
        score = score - 30
        table.insert(factors, "MP不足时选择高消耗技能")
    elseif context.character_status.is_critical_health and not context.decision_type.is_defensive then
        score = score - 10
        table.insert(factors, "低生命值时未优先自保")
    end

    return {
        score = math.max(0, math.min(100, score)),
        factors = factors,
        assessment = self:generate_factor_assessment(score, factors)
    }
end

-- 评估适应性
function AIQualityAssessor:assess_adaptability(context)
    local score = 50
    local factors = {}

    -- 根据战斗规模调整策略
    if context.battle_analysis.alive_enemies > context.battle_analysis.alive_allies then
        if context.decision_type.is_defensive or context.decision_type.is_supportive then
            score = score + 20
            table.insert(factors, "人数劣势时选择保守策略")
        end
    elseif context.battle_analysis.team_advantage > 1.5 then
        if context.decision_type.is_offensive then
            score = score + 15
            table.insert(factors, "人数优势时选择进攻策略")
        end
    end

    -- 评估对队友状态的反应
    if context.battle_analysis.low_health_allies > 0 then
        local support_ratio = 0
        if context.decision_type.is_supportive then
            support_ratio = 1
        elseif context.decision_type.is_defensive then
            support_ratio = 0.5
        end

        score = score + support_ratio * 20
        if support_ratio > 0 then
            table.insert(factors, "对队友状态做出适当反应")
        end
    end

    -- 评估对威胁的响应
    if context.target_analysis and context.target_analysis.threat_level > 2.0 then
        if context.decision_type.is_offensive then
            score = score + 15
            table.insert(factors, "优先处理高威胁目标")
        end
    end

    return {
        score = math.max(0, math.min(100, score)),
        factors = factors,
        assessment = self:generate_factor_assessment(score, factors)
    }
end

-- 评估资源管理
function AIQualityAssessor:assess_resource_management(context)
    local score = 50
    local factors = {}

    -- MP管理评估
    if context.character_status.is_low_mp then
        if context.decision_type.resource_cost == 0 then
            score = score + 25
            table.insert(factors, "MP不足时选择无消耗行动")
        elseif context.decision_type.resource_cost <= context.character.mp * 0.5 then
            score = score + 10
            table.insert(factors, "MP不足时合理控制消耗")
        else
            score = score - 20
            table.insert(factors, "MP不足时消耗过多")
        end
    else
        if context.decision_type.resource_cost > context.character.mp * self.config.thresholds.resource_waste_threshold then
            score = score - 10
            table.insert(factors, "MP充足但消耗过大")
        end
    end

    -- 物品管理评估
    if context.decision.type == "item" then
        local item_value = self:evaluate_item_usage(context)
        score = score + item_value
        table.insert(factors, item_value > 0 and "合理使用物品" or "物品使用时机不当")
    end

    return {
        score = math.max(0, math.min(100, score)),
        factors = factors,
        assessment = self:generate_factor_assessment(score, factors)
    }
end

-- 评估风险
function AIQualityAssessor:assess_risk_assessment(context)
    local score = 70 -- 默认较好分数，因为大部分AI决策是低风险的
    local factors = {}

    -- 评估决策风险
    local risk_level = self:calculate_decision_risk(context)

    if risk_level <= self.config.thresholds.acceptable_risk_level then
        score = score + 15
        table.insert(factors, "低风险决策")
    elseif risk_level > 0.6 then
        score = score - 20
        table.insert(factors, "高风险决策")
    end

    -- 评估在危机状态下的风险控制
    if context.character_status.is_critical_health then
        if context.decision_type.is_defensive then
            score = score + 10
            table.insert(factors, "危机状态下的保守选择")
        elseif context.decision_type.is_offensive and context.battle_analysis.team_advantage < 1.0 then
            score = score - 15
            table.insert(factors, "危机状态下冒险进攻")
        end
    end

    return {
        score = math.max(0, math.min(100, score)),
        factors = factors,
        assessment = self:generate_factor_assessment(score, factors),
        risk_level = risk_level
    }
end

-- 计算决策风险
function AIQualityAssessor:calculate_decision_risk(context)
    local risk = 0

    -- 基于角色状态的风险
    if context.character_status.is_critical_health then
        risk = risk + 0.3
    end

    -- 基于决策类型的风险
    if context.decision_type.is_offensive then
        risk = risk + 0.2
    end

    -- 基于战斗环境的风险
    if context.battle_analysis.team_advantage < 1.0 then
        risk = risk + 0.2
    end

    -- 基于资源状况的风险
    if context.character_status.is_low_mp then
        risk = risk + 0.1
    end

    return math.min(1.0, risk)
end

-- 计算综合评分
function AIQualityAssessor:calculate_overall_score(assessment_results)
    local weights = self.config.quality_weights
    local total_score = 0

    total_score = total_score + assessment_results.strategic_correctness.score * weights.strategic_correctness
    total_score = total_score + assessment_results.efficiency.score * weights.efficiency
    total_score = total_score + assessment_results.adaptability.score * weights.adaptability
    total_score = total_score + assessment_results.resource_management.score * weights.resource_management
    total_score = total_score + assessment_results.risk_assessment.score * weights.risk_assessment

    return math.max(0, math.min(100, total_score))
end

-- 获取等级信息
function AIQualityAssessor:get_grade_info(score)
    for _, level_info in pairs(self.config.score_levels) do
        if score >= level_info.min then
            return {
                grade = level_info.grade,
                description = level_info.description
            }
        end
    end

    return {grade = "F", description = "无效决策"}
end

-- 生成评估总结
function AIQualityAssessor:generate_assessment_summary(assessment_results, overall_score)
    local summary_parts = {}

    -- 找出最高和最低的评估维度
    local dimensions = {
        {name = "战略正确性", result = assessment_results.strategic_correctness},
        {name = "效率性", result = assessment_results.efficiency},
        {name = "适应性", result = assessment_results.adaptability},
        {name = "资源管理", result = assessment_results.resource_management},
        {name = "风险评估", result = assessment_results.risk_assessment}
    }

    table.sort(dimensions, function(a, b) return a.result.score > b.result.score end)

    if #dimensions > 0 then
        table.insert(summary_parts, string.format("最佳表现：%s (%.1f分)", dimensions[1].name, dimensions[1].result.score))
        table.insert(summary_parts, string.format("待改进：%s (%.1f分)", dimensions[#dimensions].name, dimensions[#dimensions].result.score))
    end

    return table.concat(summary_parts, "；")
end

-- 生成因素评估
function AIQualityAssessor:generate_factor_assessment(score, factors)
    if #factors == 0 then
        return "无特殊因素影响"
    end

    local assessment = "影响因素：" .. table.concat(factors, "；")
    if score >= 80 then
        return assessment .. " (优秀)"
    elseif score >= 60 then
        return assessment .. " (良好)"
    else
        return assessment .. " (需改进)"
    end
end

-- 生成改进建议
function AIQualityAssessor:generate_recommendations(context, assessment_results)
    local recommendations = {}

    -- 基于各个维度的评分生成建议
    if assessment_results.strategic_correctness.score < 70 then
        table.insert(recommendations, "改善战略判断：优先处理高威胁目标和低生命值单位")
    end

    if assessment_results.efficiency.score < 70 then
        table.insert(recommendations, "提高资源效率：选择性价比更高的技能和行动")
    end

    if assessment_results.adaptability.score < 70 then
        table.insert(recommendations, "增强战术适应性：根据战斗规模和队友状态调整策略")
    end

    if assessment_results.resource_management.score < 70 then
        table.insert(recommendations, "优化资源管理：合理控制MP消耗，节约使用物品")
    end

    if assessment_results.risk_assessment.score < 70 then
        table.insert(recommendations, "改进风险评估：避免在不利状态下冒险")
    end

    -- 基于当前状态生成具体建议
    if context.character_status.is_critical_health then
        table.insert(recommendations, "当前生命值极低，优先使用治疗技能或防御")
    end

    if context.character_status.is_low_mp then
        table.insert(recommendations, "当前MP不足，优先使用无消耗或低消耗技能")
    end

    return recommendations
end

-- 评估物品使用价值
function AIQualityAssessor:evaluate_item_usage(context)
    local value = 0

    if context.decision.type == "item" and context.decision.item then
        -- 简化的物品价值评估
        if context.decision.item.type == "consumable" then
            if context.character_status.is_critical_health then
                value = 20
            elseif context.character_status.health_percentage < 0.7 then
                value = 10
            else
                value = -5 -- 生命值充足时使用消耗品浪费
            end
        end
    end

    return value
end

-- 记录决策历史
function AIQualityAssessor:record_decision(character, decision, assessment)
    local record = {
        character_id = character.id,
        decision_type = decision.type,
        score = assessment.overall_score,
        grade = assessment.grade,
        timestamp = assessment.timestamp
    }

    table.insert(self.decision_history, record)

    -- 更新性能指标
    self:update_performance_metrics(assessment)

    -- 保持历史记录在合理范围内
    if #self.decision_history > 1000 then
        table.remove(self.decision_history, 1)
    end
end

-- 更新性能指标
function AIQualityAssessor:update_performance_metrics(assessment)
    self.performance_metrics.total_decisions = self.performance_metrics.total_decisions + 1

    if assessment.overall_score >= 90 then
        self.performance_metrics.excellent_decisions = self.performance_metrics.excellent_decisions + 1
    elseif assessment.overall_score < 60 then
        self.performance_metrics.poor_decisions = self.performance_metrics.poor_decisions + 1
    end

    -- 更新平均分数
    local total_score = self.performance_metrics.average_score * (self.performance_metrics.total_decisions - 1) + assessment.overall_score
    self.performance_metrics.average_score = total_score / self.performance_metrics.total_decisions

    -- 更新改进趋势
    if self.performance_metrics.total_decisions % 10 == 0 then
        local recent_score = 0
        local count = 0

        for i = math.max(1, #self.decision_history - 9), #self.decision_history do
            recent_score = recent_score + self.decision_history[i].score
            count = count + 1
        end

        if count > 0 then
            table.insert(self.performance_metrics.improvement_trend, recent_score / count)

            -- 保持趋势记录在合理范围内
            if #self.performance_metrics.improvement_trend > 50 then
                table.remove(self.performance_metrics.improvement_trend, 1)
            end
        end
    end
end

-- 获取性能报告
function AIQualityAssessor:get_performance_report()
    local metrics = self.performance_metrics

    local report = {
        total_decisions = metrics.total_decisions,
        excellent_rate = metrics.total_decisions > 0 and (metrics.excellent_decisions / metrics.total_decisions * 100) or 0,
        poor_rate = metrics.total_decisions > 0 and (metrics.poor_decisions / metrics.total_decisions * 100) or 0,
        average_score = metrics.average_score,
        improvement_trend = metrics.improvement_trend,

        -- 计算改进趋势
        trend_analysis = self:analyze_improvement_trend()
    }

    return report
end

-- 分析改进趋势
function AIQualityAssessor:analyze_improvement_trend()
    local trend = self.performance_metrics.improvement_trend

    if #trend < 3 then
        return "数据不足"
    end

    local recent_avg = 0
    for i = #trend - 2, #trend do
        recent_avg = recent_avg + trend[i]
    end
    recent_avg = recent_avg / 3

    local earlier_avg = 0
    for i = 1, math.min(3, #trend - 3) do
        earlier_avg = earlier_avg + trend[i]
    end
    earlier_avg = earlier_avg / math.min(3, #trend - 3)

    local improvement = recent_avg - earlier_avg

    if improvement > 5 then
        return string.format("显著改进 (+%.1f)", improvement)
    elseif improvement > 1 then
        return string.format("轻微改进 (+%.1f)", improvement)
    elseif improvement < -5 then
        return string.format("显著下降 (%.1f)", improvement)
    elseif improvement < -1 then
        return string.format("轻微下降 (%.1f)", improvement)
    else
        return "保持稳定"
    end
end

-- 获取详细的性能分析
function AIQualityAssessor:get_detailed_analysis()
    local report = self:get_performance_report()

    -- 添加决策类型分析
    local type_analysis = {}
    for _, record in ipairs(self.decision_history) do
        type_analysis[record.decision_type] = (type_analysis[record.decision_type] or 0) + 1
    end

    -- 添加等级分布
    local grade_distribution = {}
    for _, record in ipairs(self.decision_history) do
        grade_distribution[record.grade] = (grade_distribution[record.grade] or 0) + 1
    end

    return {
        performance_report = report,
        decision_type_distribution = type_analysis,
        grade_distribution = grade_distribution,
        total_history_records = #self.decision_history
    }
end

-- 导出模块
return AIQualityAssessor